import React, { Fragment } from 'react';
import {
  Layout,
  Menu,
  Drawer,
  Divider,
  Space,
  Dropdown,
  message,
  List,
  Switch,
  Popconfirm,
} from 'antd';
import '@ant-design/pro-layout/dist/layout.min.css';
import './index.css';
import './ThemeColor.less';
import navTheme_dark from '../assets/navTheme_dark.svg';
import navTheme_light from '../assets/navTheme_light.svg';
import TopHeader from '@/components/Layout/TopHeader';
import BlockCheckbox from './BlockCheckbox';
import { renderLayoutSettingItem } from './LayoutChange';
import getLocales from '../locales';
import PrimaryLayout from './PrimaryLayout';
import MicroAppLayout from './MicroAppLayout';
import themeArr from '../../config/themeMap.js';
import themeAppArr from '../../config/themeAppArr.js';

import { getLayout, checkIsMaster } from '@/utils/layout';
import { Scrollbars } from 'react-custom-scrollbars';
import {
  ReloadOutlined
} from '@ant-design/icons';
import { getCacheData } from '../utils/utils'

// 获取设置参数缓存对象
var themeHeaderData = getCacheData({ key: 'themeHeader' })

// 确认重置系统设置
const confirm = function () {
  this.resetSetting()
}

// Body组件
interface BodyProps {
  title: string;
}
const Body: React.FC<BodyProps> = ({ children, title }) => (
  <div style={{ marginBottom: 24 }}>
    <h3 className="ant-pro-setting-drawer-title">{title}</h3>
    {children}
  </div>
);

// 获取当前语言
export const getFormatMessage = (): ((data: {
  id: string;
  defaultMessage?: string;
}) => string) => {
  const formatMessage = ({
    id,
    defaultMessage,
  }: {
    id: string;
    defaultMessage?: string;
  }): string => {
    const locales = getLocales();
    if (locales[id]) {
      return locales[id];
    }
    if (defaultMessage) {
      return defaultMessage as string;
    }
    return id;
  };
  return formatMessage;
};

// 获取当前设置对象
const getThemeList = () => {
  const formatMessage = getFormatMessage();
  const list: {
    key: string;
    fileName: string;
    modifyVars: {
      '@primary-color': string;
    };
    theme: 'dark' | 'light';
  }[] = (window as any).umi_plugin_ant_themeVar || [];
  const themeList = [
    {
      key: 'light',
      url: navTheme_light,
      title: formatMessage({ id: 'app.setting.pagestyle.light' }),
    },
    {
      key: 'dark',
      url: navTheme_dark,
      title: formatMessage({
        id: 'app.setting.pagestyle.dark',
        defaultMessage: '',
      }),
    },
  ];

  const darkColorList: {
    key: string;
    color: string;
    theme: 'dark' | 'light';
  }[] = [
      {
        key: 'daybreak',
        color: '#1890ff',
        theme: 'dark',
      },
    ];

  const lightColorList: {
    key: string;
    color: string;
    theme: 'dark' | 'light';
  }[] = [
      {
        key: 'daybreak',
        color: '#1890ff',
        theme: 'dark',
      },
    ];

  // insert  theme color List
  list.forEach((item) => {
    const color = (item.modifyVars || {})['@primary-color'];
    if (item.theme === 'dark' && color) {
      darkColorList.push({
        color,
        ...item,
      });
    }
    if (!item.theme || item.theme === 'light') {
      lightColorList.push({
        color,
        ...item,
      });
    }
  });

  return {
    colorList: {
      dark: darkColorList,
      light: lightColorList,
    },
    themeList,
  };
};


// 调用
const formatMessage = getFormatMessage();
const themeList = getThemeList();
let pathList: any = [];

// 布局类型
const LayoutMap = {
  primaryLayout: PrimaryLayout,
  microAppLayout: MicroAppLayout,
};

class BasicLayout extends React.Component {
  state = {
    renderList: [],
    // microAppLoading: true,
    // placement: 'right',
    visible: false,
    currentAppName: '', // 当前选中的应用
    menuMode: themeHeaderData.menuMode || 'inline',
    isPass: true,
    navTheme: themeHeaderData.navTheme || 'light',
    layout: themeHeaderData.layout || 'sidemenu',
    othersettings: {
      colorWeak: !!themeHeaderData.othersettings.colorWeak,
      navShow: !!themeHeaderData.othersettings.navShow,
      menuShow: !!themeHeaderData.othersettings.menuShow,
      logoShow: !!themeHeaderData.othersettings.logoShow,
    }
  };

  componentWillMount() {}

  componentDidMount() {
    console.log('f5 refresh BasicLayout componentDidMount');
  }

  getCurrentAppInfo(objStr, appName) {
    const obj = JSON.parse(objStr);
    for (let i = 0; i < obj.length; i++) {
      let item = obj[i];
      if (String(item.appName) === appName) {
        return item;
      }
    }
    return null;
  }

  toggle = () => {
    this.setState({
      collapsed: !this.state.collapsed,
    });
  };

  changeAppName = (appName) => {
    console.log('ok');
    this.setState({
      currentAppName: appName,
    });
  };

  showSysSetting = () => {
    this.setState({
      visible: true,
    });
  };

  // 关闭设置面板
  onClose = (x) => {
    // 只有点击遮罩层的时候关闭
    if (x.target.tagName == 'DIV') {
      this.setState({
        visible: false,
      });
    }

  };

  // 改变左边菜单布局
  handleMenuChange(e: any) {
    let obj = themeHeaderData
    obj.menuMode = e.key == '1' ? 'inline' : 'vertical'
    this.setState({
      menuMode: e.key == '0' ? 'vertical' : 'inline'
    });
    message.success('切换成功');
    window.localStorage.setItem('themeHeader', JSON.stringify(obj));
    // window.location.reload()
  }

   /**
 * 修改设置
 * @param key
 * @param value
 * @param hideMessageLoading
 */
  changeSetting = (
    key: string,
    value: string | boolean,
    hideMessageLoading?: boolean,
  ) => {
    let obj = themeHeaderData
    if (key === 'navTheme') {
      this.setState({ navTheme: value })
      obj.navTheme = value
    }
    if (key === 'layout') {
      this.setState({ layout: value })
      obj.layout = value
    }
    if (key == "colorWeak" || key == "navShow" || key == "menuShow" || key == "logoShow") {
      obj['othersettings'][key] = value
      this.setState({ othersettings: obj['othersettings'] })

    }
    if (key == "colorWeak") {
      document.querySelectorAll('body')[0].style.filter = value ? 'invert(80%)' : ''
      document.querySelectorAll('#root')[0].style.filter = value ? 'invert(80%)' : ''
    }
    localStorage.themeHeader = JSON.stringify(obj)
  };

  // 改变导航主题
  changeTheme = (key: string) => {
    const index = themeArr.findIndex((element: any) => element.name === key);
    let ele: any = document.getElementById('root');
    ele.className = `${themeArr[index].name}`;
    localStorage.themeHeader = (() => {
      let obj = themeHeaderData
      obj.name = themeArr[index].name
      return JSON.stringify(obj)
    })()
    message.success('主题切换成功');
  };

  // 改变主题色
  changeThemeApp = (_x: any, _key: string) => {
    let obj = getCacheData({ key: 'themeApp' })
    obj[_key] = `${_x[_key]} !important`
    window.less.modifyVars(obj)
    localStorage.themeApp = JSON.stringify(obj);
    message.success('主题切换成功');
  };

  // 改变左边菜单布局
  handleMenuChange(e: any) {
    let obj = themeHeaderData
    obj.menuMode = e.key == '1' ? 'inline' : 'vertical'
    this.setState({
      menuMode: e.key == '0' ? 'vertical' : 'inline'
    });
    message.success('切换成功');
    window.localStorage.setItem('themeHeader', JSON.stringify(obj));
    // window.location.reload()
  }

  // 重置设置
  resetSetting = () => {
    this.setState({
      menuMode: 'inline',
      navTheme: 'light',
      layout: 'sidemenu',
      othersettings: {
        colorWeak: false,
        menuShow: true,
        logoShow: true,
      }
    })
    window.less.modifyVars({})
    document.getElementById('root').className = 'theme1'
    document.getElementById('root').style.filter = ''
    document.querySelectorAll('body')[0].style.filter = ''
    window.localStorage.setItem(
      'themeHeader',
      JSON.stringify({ othersettings: { colorWeak: false, menuShow: true, logoShow: true } }),
    );
    window.localStorage.setItem(
      'themeApp',
      '{}'
    );
    message.success('系统已重置设置项！');
  }


  render() {
    const pathname = this.props.location.pathname;

    // 判断使用什么布局
    const Container = LayoutMap[getLayout(pathname)];
    // 获取应用名称
    var pathArr = pathname.split('/');
    var topPath = pathname;
    console.log(pathArr);
    if (pathArr && pathArr.length > 1) {
      topPath = '/' + pathArr[1];
    }
    console.log(pathname);

    // 优先从状态中获取，没有则从本地缓存中获取当前应用信息
    const currentAppList = window.sessionStorage.getItem('currentAppList');
    var appEntry = null;
    var appName = null;
    if (pathArr[1] != '' && !checkIsMaster(pathname) && currentAppList) {
      //TODO sessionStorage 丢失的问题,session丢失之后去根据应用名称去获取应用信息
      const currentAppInfo = this.getCurrentAppInfo(currentAppList, pathArr[1]);
      if (currentAppInfo) {
        console.log(currentAppInfo);
        appEntry = currentAppInfo.appPath;
        appName = currentAppInfo.appName;
      }
    }

    // 顶部导航数据
    const headerProps = {
      pathname: pathname,
      appName: appName,
      notifications: [
        {
          title: 'flyray devui',
        },
        {
          title: 'flyray devui',
        },
      ],
      collapsed: this.state.collapsed,
    };

    const containerProps = {
      pathname: pathname,
      appName: appName,
      appEntry: appEntry,
      randomNum: Math.random()
    };

    // 菜单主题切换menu
    const menu = (
      <Menu onClick={this.handleMenuChange.bind(this)}>
        <Menu.Item key="0">垂直</Menu.Item>
        <Menu.Item key="1">内嵌</Menu.Item>
      </Menu>
    );

    // 菜单皮肤设置
    const navTheme = (
      <Body
        title={formatMessage({
          id: 'app.setting.pagestyle',
          defaultMessage: 'Page style setting',
        })}
      >
        <BlockCheckbox
          list={themeList.themeList}
          value={this.state.navTheme}
          onChange={(value) => this.changeSetting('navTheme', value, false)}
        />
      </Body>
    )

    // 菜单位置设置
    const menuPosition = (
      <Body title={formatMessage({ id: 'app.setting.navigationmode' })}>
        <BlockCheckbox
          value={this.state.layout}
          onChange={(value) => this.changeSetting('layout', value, false)}
        />
      </Body>
    )

    // 导航主题设置
    const navigation = (
      <div>
        <h3 className="ant-pro-setting-drawer-title">导航主题设置</h3>
        <ul className="ulStyle">
          {
            themeAppArr.map((x, i) => {
              if (i < 4) {
                return <li
                  key={i}
                  onClick={() => {
                    this.changeTheme(`theme${i + 1}`);
                  }}
                ></li>
              }
            })
          }
        </ul>
      </div>
    );

    // 主题色设置
    const primaryNavigation = (
      <div>
        <h3 className="ant-pro-setting-drawer-title">主题色</h3>
        <ul className="ulStyle">
          {
            themeAppArr.map((x, i) => {
              if (i < 6) {
                return <li
                  key={i}
                  onClick={() => {
                    this.changeThemeApp(x, '@primary-color');
                  }}
                  style={(() => {
                    const value = x['@primary-color']
                    const obj = { 'backgroundColor': value }
                    return obj
                  })()}
                ></li>
              }

            })
          }
        </ul>
      </div>
    );

    // 字体颜色设置
    const fontNavigation = (
      <div>
        <h3 className="ant-pro-setting-drawer-title">字体颜色设置</h3>
        <ul className="ulStyle">
          {
            themeAppArr.map((x, i) => {
              if (i < 4) {
                return <li
                  key={i}
                  onClick={() => {
                    this.changeThemeApp(x, '@text-color');
                  }}
                  style={(() => {
                    const value = x['@text-color']
                    const obj = { 'backgroundColor': value }
                    return obj
                  })()}
                ></li>
              }
            })
          }
        </ul>
      </div>
    );

    // 菜单布局设置
    const menuStyle = (
      <div style={{ marginTop: 30 }}>
        <h3 className="ant-pro-setting-drawer-title"> 菜单布局</h3>
        <Space>
          <span>当前菜单样式：</span>
          <Dropdown overlay={menu} trigger={['hover']}>
            <div
              style={{
                cursor: 'pointer',
                border: '1px solid black',
                padding: '0 5px',
              }}
            >
              {(() => {
                if (!this.state.menuMode) return '内嵌'
                return this.state.menuMode == 'inline' ? '内嵌' : '垂直'
              })()}
            </div>
          </Dropdown>
        </Space>
      </div>
    );

    // 其他设置
    const otherSettings = (
      <Body title={formatMessage({ id: 'app.setting.othersettings' })}>
        <List
          split={false}
          renderItem={renderLayoutSettingItem}
          dataSource={[
            // {
            //   title: formatMessage({ id: 'app.setting.navName' }),
            //   action: (
            //     <Switch
            //       size="small"
            //       checked={!!this.state.othersettings.navShow}
            //       onChange={(checked) => this.changeSetting('navShow', checked)}
            //     />
            //   ),
            // },
            {
              title: formatMessage({ id: 'app.setting.menuName' }),
              action: (
                <Switch
                  size="small"
                  checked={!!this.state.othersettings.menuShow}
                  onChange={(checked) => this.changeSetting('menuShow', checked)}
                />
              ),
            },
            {
              title: formatMessage({ id: 'app.setting.logoName' }),
              action: (
                <Switch
                  size="small"
                  checked={!!this.state.othersettings.logoShow}
                  onChange={(checked) => this.changeSetting('logoShow', checked)}
                />
              ),
            },
            {
              title: formatMessage({ id: 'app.setting.weakmode' }),
              action: (
                <Switch
                  size="small"
                  checked={!!this.state.othersettings.colorWeak}
                  onChange={(checked) => this.changeSetting('colorWeak', checked)}
                />
              ),
            },
          ]}
        />
      </Body>
    )

    const { placement, visible } = this.state;

    return (
      <Fragment>
        <Layout>
          <TopHeader {...headerProps} showSysSetting={this.showSysSetting} />
          <Container {...containerProps}>{this.props.children}</Container>
        </Layout>
        <Drawer
            title="系统设置"
            placement="right"
            closable={true}
            onClose={this.onClose}
            visible={visible}
            key="right"
            closeIcon={<Popconfirm title="您确定要重置系统设置吗？" onConfirm={confirm.bind(this)}><ReloadOutlined /></Popconfirm>}
          >
            {navTheme}
            {navigation}
            {primaryNavigation}
            {menuPosition}
            {fontNavigation}
            {menuStyle}
            <Divider />
            {otherSettings}
          </Drawer>
      </Fragment>
    );
  }
}

export default BasicLayout;
